package com.otod.commons.servlet;


import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.otod.base.exception.AppException;
import com.otod.commons.auth.SessionUserHolder;
import com.otod.commons.auth.SessionUserUtil;
import com.otod.commons.constants.AttachmentConstant;
import com.otod.commons.constants.CommonConstant;
import com.otod.commons.constants.PropertiesConstant;
import com.otod.commons.filemanger.SmartFile;
import com.otod.commons.filemanger.SmartRequest;
import com.otod.commons.filemanger.SmartUpload;
import com.otod.commons.filemanger.SmartUploadException;
import com.otod.commons.filemanger.bo.FileBasicInfo;
import com.otod.commons.filemanger.service.IUploadSingleService;
import com.otod.commons.tools.UserEnv;
import com.otod.commons.utils.Code;
import com.otod.commons.utils.Collections3;
import com.otod.commons.utils.DateUtils;
import com.otod.commons.utils.FileUtil;
import com.otod.commons.utils.RandomUtil;
import com.otod.commons.utils.SpringContextHolder;
import com.otod.commons.utils.StringUtils;
import com.otod.pm.doc.service.PmDocItemService;
import com.otod.pm.doc.vo.PmDocItemVo;
import com.otod.sys.file.service.IFileService;
import com.otod.sys.vo.FileVo;

/**
 * @author jqiu
 */
public class UploadServlet extends HttpServlet {
	private static Logger logger = LoggerFactory.getLogger(UploadServlet.class);
	
	private static String PATH = UserEnv.getProp(PropertiesConstant.UPLOAD_FILE_PATH);

	private static final long serialVersionUID = 1L;
	
	private ServletConfig config;

    /**
     * Init the servlet
     */
    final public void init(ServletConfig config) throws ServletException {
        this.config = config;
    }

    final public ServletConfig getServletConfig() {
        return config;
    }

    /**
     * 处理下载请求
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	if("delete".equals(request.getParameter("opType"))){
    		deleteFile(request, response);
    	}else{
    		downloadFile(request, response);
    	}
    }

    /**
     * 处理上传请求
     * @param httpServletRequest
     * (
     * 		type:	附件导入类型
     * 				AttachmentConstant.ATTACH_EXCELIMPORT 		Excel导入
     * 					{templateName:模板名}
     * 				AttachmentConstant.ATTACH_COMMONMANAGE		写统一附件管理表的类型
     * 					{
     * 						busiId:		对应业务功能ID
     * 						replaceOld:	是否替换原有上传文件
     * 					}
     * 				AttachmentConstant.ATTACH_BASIC				基本文件上传（他们走IUploadService和IDownloadService接口）
     * 					{
     * 						beanName:	IUploadSingleService bean id
     * 					}
     * 				其它值或不传										其它类型附件上传
     * 		funcType：	功能类型，每一个功能对应一个常量配置;funcType不为空时 type 被设置成 AttachmentConstant.ATTACH_COMMONMANAGE
     * 				
     * 				
     * 				
     * )
     * @param httpServletResponse
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
        	request.setCharacterEncoding("utf-8");
        	String sysAllowfileExt = UserEnv.getProp(PropertiesConstant.UPLOAD_FILE_SUFFIX);
        	 String type = request.getParameter("type");		
        	 String allowfileExt = request.getParameter("allowfileExt");											//允许上传的扩展名
             String funcType = request.getParameter("funcType");													//如果功能类型不为空，则默认为通用文件上传类型
//             if(!StringUtils.isEmpty(funcType)){
//             	type = AttachmentConstant.ATTACH_COMMONMANAGE;
//             }
        	SmartUpload mySmartUpload = new SmartUpload();
//        	mySmartUpload.setMaxFileSize(Long.parseLong(CrmEnv.getProp(PropertiesConstant.UPLOAD_FILE_MAX_SIZE))*1024);		//文件大小限制
        	mySmartUpload.setMaxFileSize(5242880000L);		//文件大小限制8000M
        	if(AttachmentConstant.ATTACH_EXCELIMPORT.equals(type)){															//excel导入
        		mySmartUpload.setAllowedFilesList("xls,xlsx");																//文件类型限制为excel
        	}else if(!StringUtils.isEmpty(allowfileExt)){
        		String allowfileExtTemp = sysAllowfileExt;						//request后允许上传的文件必须是properties中配置的允许上传的文件类型
//        		String allowfileExtTemp = ","+CrmEnv.getProp(PropertiesConstant.UPLOAD_FILE_TYPES)+",";						//request后允许上传的文件必须是properties中配置的允许上传的文件类型
        		String[] allowfileExtArray = allowfileExt.split(",");
        		StringBuffer fileExtSb = new StringBuffer();
        		for (String fileExt : allowfileExtArray) {
					if(allowfileExtTemp.indexOf(","+fileExt+",")>-1){
						fileExtSb.append(",");
						fileExtSb.append(fileExt);
					}else{
						throw new AppException("request中配置的允许文件上传类型【"+fileExt+"】不包括在系统配置的允许上传类型中");
					}
				}
        		mySmartUpload.setAllowedFilesList(fileExtSb.substring(1));
//        		mySmartUpload.setAllowedFilesList(fileExtSb.length()>0?fileExtSb.substring(1):CrmEnv.getProp(PropertiesConstant.UPLOAD_FILE_TYPES));
        	}else{
        		mySmartUpload.setAllowedFilesList(sysAllowfileExt);					//文件类型限制
//        		mySmartUpload.setAllowedFilesList(CrmEnv.getProp(PropertiesConstant.UPLOAD_FILE_TYPES));					//文件类型限制
        	}
            mySmartUpload.initialize(config, request, response); 												// Initialization
            mySmartUpload.upload();																				// Upload
            
            if(mySmartUpload.getFiles().getCount()==0 || mySmartUpload.getFiles().getFile(0).isMissing()){
            	throw new AppException("没有成功上传文件！");
            }
            
            String ret;
//            if(AttachmentConstant.ATTACH_EXCELIMPORT.equals(type)){												//excel导入
//            	ret = this.excelImport(request, response, mySmartUpload);
//            }else 
//            if(AttachmentConstant.ATTACH_COMMONMANAGE.equals(type)){										//写统一附件管理表的类型
//            	ret = this.commonUpload(request, response, mySmartUpload);
//            }else 
            if(AttachmentConstant.ATTACH_INTERFACE.equals(type)){												//基本文件上传（他们走IUploadService和IDownloadService接口）
            	ret = this.interfaceUpload(request, response, mySmartUpload);
//            }else{																								//其它类型附件上传
//            	ret = this.otherUpload(request, response, mySmartUpload);
            }else{
            	ret = this.commonUpload(request, response, mySmartUpload);
            }
            
//            request.setAttribute("ret", ret);
//        	String fileList = "/jsp/public/attachment/uploadTarget.jsp";
//			request.getRequestDispatcher(fileList).forward(request, response);
            	
            	
            	/*
				 * 注：插件需要服务器端返回JSON格式的字符串，且必须以下面的格式来返回，一个字段都不能少
				 *     如果上传失败，那么则须用特定格式返回信息：
				 *      "name": "picture1.jpg",
    					"size": 902604,
    					"error": "Filetype not allowed"
    				   另外，files必须为一个JSON数组，哪怕上传的是一个文件
				 */
            response.setContentType("application/json; charset=UTF-8");
			response.getWriter().print(ret);
        }catch (SmartUploadException se){
        	se.printStackTrace();
        	
        	response.setContentType("application/json");
        	response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        	JSONArray ja = new JSONArray();
        	JSONObject json = new JSONObject();
			json.put("error", "上传出错啦");
			ja.add(json);
			response.getWriter().print(json.toString());
        } catch (AppException e){
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        	JSONArray ja = new JSONArray();
        	JSONObject json = new JSONObject();
			json.put("error", e.getMsg());
			ja.add(json);
			response.getWriter().print(json.toString());
        } catch (Exception e){
        	e.printStackTrace();
        	
        	response.setContentType("application/json");
        	response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        	JSONArray ja = new JSONArray();
        	JSONObject json = new JSONObject();
			json.put("error", "上传出错啦");
			ja.add(json);
			response.getWriter().print(json.toString());
		} 
    }

    /**
     * Destroy the servlet
     */
    public void destroy() {
    }
    
    
    /**
     * 文件删除
     * @param request
     * @param response
     * @throws javax.servlet.ServletException
     * @throws java.io.IOException
     */
    public void deleteFile(HttpServletRequest request, HttpServletResponse response)  throws ServletException,IOException {
    	String id = Code.decode(request.getParameter("sname"));
	    try{
	    	IFileService busiFileInfo = (IFileService)SpringContextHolder.getBean(IFileService.BEAN_ID); 
	    	FileVo bo = busiFileInfo.getById(id);
	    	if(bo == null){
	    		throw new AppException("文件不存在,可能已经删除！");
	    	}
	    	busiFileInfo.deleteById(id);
	    	
	    	PATH = bo.getFileServerPath();
	    	String serverFilename = bo.getFileName();
	    	String fullPath = PATH + bo.getFileServerName();
	    	
	    	FileUtil.deleteFile(fullPath);
	    	
            request.setAttribute("ret", "成功删除【"+serverFilename+"】");
        	String fileList = "/jsp/public/attachment/downLoadTarget.jsp";
			request.getRequestDispatcher(fileList).forward(request, response);
    	} catch (AppException e){
            request.setAttribute("error", e.getMsg());
        	String fileList = "/jsp/public/attachment/downLoadTarget.jsp";
			request.getRequestDispatcher(fileList).forward(request, response);
		} catch (Exception e){
        	e.printStackTrace();
        	request.setAttribute("error", "下载失败");
        	String fileList = "/jsp/public/attachment/downLoadTarget.jsp";
        	request.getRequestDispatcher(fileList).forward(request, response);
		}
    }
    
    
    /**
     * 文件下载
     * @param request
     * @param response
     * @throws javax.servlet.ServletException
     * @throws java.io.IOException
     */
    public void downloadFile(HttpServletRequest request, HttpServletResponse response)  throws ServletException,IOException {
    	String path;
    	String serverFilename = Code.decode(request.getParameter("sname"));
    	String clientFileName = Code.decode(request.getParameter("cname"));
        String contentDisposition = request.getParameter("contentDisposition");
        String searchByBusid = request.getParameter("isBusid");														//sname为业务ID
        SmartUpload su = new SmartUpload();																		// 新建一个SmartUpload对象
        su.initialize(config, request, response);																// 初始化
        /*设定contentDisposition为null以禁止浏览器自动打开文件，
        保证点击链接后是下载文件。若不设定，则下载的文件扩展名为doc时，
        浏览器将自动用word打开它。扩展名为pdf时，浏览器将用acrobat打开*/
        if(StringUtils.isNotEmpty(contentDisposition)){
        	su.setContentDisposition(contentDisposition);
        }else{
        	su.setContentDisposition(null);
        }
        String fullPath = "";
        try {
        	if(StringUtils.isEmpty(serverFilename)){
        		throw new AppException("文件名不能为空");
        	}
        	if(StringUtils.isEmpty(clientFileName)){
        		clientFileName = serverFilename;
        	}
        	String type = request.getParameter("type");		
        	if(AttachmentConstant.ATTACH_EXCELIMPORT.equals(type)){												//excel导入
            	path = PATH + "excel" + File.separator;
            	fullPath = path + serverFilename;
            }else if(AttachmentConstant.ATTACH_COMMONMANAGE.equals(type) || AttachmentConstant.ATTACH_PDF.equals(type)){										//写统一附件管理表的类型
            	IFileService busiFileInfo = (IFileService)SpringContextHolder.getBean(IFileService.BEAN_ID); 
            	FileVo bo = null;
            	if("true".equals(searchByBusid)){
            		List<FileVo> list = busiFileInfo.queryFileByBusiId(serverFilename);
            		if(Collections3.isNotEmpty(list)){
            			bo = list.get(0);
            		}
            	}else{
            		bo = busiFileInfo.getById(serverFilename);
            	}
            	if(bo == null){
            		if(!StringUtils.isEmpty(request.getParameter("notExistPic"))){
	            		RequestDispatcher dispatcher = request.getRequestDispatcher("/images/"+request.getParameter("notExistPic")); 
	            		dispatcher .forward(request, response); 
	            		return;
            		}
            		throw new AppException("文件不存在！");
            	}
            	path = bo.getFileServerPath();
            	clientFileName = bo.getFileName();
            	fullPath = path + bo.getFileServerName();
            	
            	if(AttachmentConstant.ATTACH_PDF.equals(type)){										//查看pdf
                	path = path + "pdf" + File.separator;
                	
        			serverFilename = bo.getUuid() + ".pdf";
        			clientFileName = serverFilename;
        			
        			fullPath = path + serverFilename;
            	}
            
//            }else if(AttachmentConstant.ATTACH_BASIC.equals(type)){										//基本文件下载（他们走IUploadService和IDownloadService接口）
//            	path = PATH + "basic" + File.separator;
//            	String beanName = request.getParameter("beanName");
//            	if(!StringUtils.isEmpty(beanName)){
//            		IDownLoadService down = (IDownLoadService)SpringContextHolder.getBean(beanName);
//                	String[] ret = down.executeOnBeforeFileDownload(serverFilename);
//                	fullPath = ret[0];
//                	clientFileName = ret[1];
//            	}else{
//            		fullPath = path + serverFilename;
//            	}
           
//            }else if(AttachmentConstant.ATTACH_EXCELTEMPLATE.equals(type)){								//excel模板下载
//            	path = CrmEnv.getProp(PropertiesConstant.EXCEL_TEMPLATE_PATH) + File.separator;
//            	if(serverFilename.indexOf(".")==-1){
//            		serverFilename = serverFilename + "." + CrmEnv.getProp("download.exceltemplate.suffix");
//            	}
//            	fullPath = path + serverFilename;
            }else if(AttachmentConstant.ATTACH_TEMP.equals(type)){										//临时文件
            	path = PATH + "temp" + File.separator;
            	fullPath = path + serverFilename;
            }else{														//其它类型附件上传
            	path = PATH;
            	fullPath = path + serverFilename;
            }
        	
        	
        	//clientFileName 扩展名处理
        	if(clientFileName.split("\\.").length == 1){
        		String[] sArray = serverFilename.split("\\.");
        		if(sArray.length>1){
        			clientFileName = clientFileName + "." + sArray[sArray.length-1]; 
        		}
        	}
            su.downloadFile(fullPath, null, clientFileName);			// 下载文件
        } catch (IOException e){
        	logger.error("文件不存在！路径："+fullPath, e);
        	request.setAttribute("error", "文件不存在！");
        	String fileList = "/jsp/public/attachment/downLoadTarget.jsp";
			request.getRequestDispatcher(fileList).forward(request, response);
        } catch (SmartUploadException e) {
        	logger.error( "文件下载出错！",e);
            request.setAttribute("error", "文件下载出错！");
        	String fileList = "/jsp/public/attachment/downLoadTarget.jsp";
			request.getRequestDispatcher(fileList).forward(request, response);
		} catch (AppException e){
            request.setAttribute("error", e.getMsg());
        	String fileList = "/jsp/public/attachment/downLoadTarget.jsp";
			request.getRequestDispatcher(fileList).forward(request, response);
		} catch (Exception e){
			logger.error( "下载失败！",e);
        	request.setAttribute("error", "下载失败");
        	String fileList = "/jsp/public/attachment/downLoadTarget.jsp";
        	request.getRequestDispatcher(fileList).forward(request, response);
		}
    }
    
    
    
    /**
     * 通用导入，附件写库
     * @param request
     * @param response
     * @param mySmartUpload
     * @return
     * @throws com.hylandtec.icrm.tl.base.exception.AppException
     * @throws java.io.IOException
     * @throws com.hylandtec.icrm.tl.common.filemanger.SmartUploadException
     * @throws javax.servlet.ServletException
     */
    public String commonUpload(HttpServletRequest request, HttpServletResponse response,SmartUpload mySmartUpload) throws AppException, IOException, SmartUploadException, ServletException{
    	 SmartRequest smartRequest = mySmartUpload.getRequest();	
         String funcType = request.getParameter("funcType")==null?mySmartUpload.getRequest().getParameter("funcType"):request.getParameter("funcType");	
//         if(StringUtils.isEmpty(funcType)){
//        	 funcType = AttachmentConstant.ATTACH_COMMONMANAGE;
//	     		throw new AppException("文件类型不能为空");
//	     }
         
         String replaceOld = request.getParameter("replaceOld")==null?mySmartUpload.getRequest().getParameter("replaceOld"):request.getParameter("replaceOld");						//是否替换原有附件，保证一个业务只有一条记录
         String busiId = request.getParameter("busiId")==null?mySmartUpload.getRequest().getParameter("busiId"):request.getParameter("busiId");
         
         JSONArray ja = new JSONArray();
//         String ret = "";																//返回信息
         for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++) {
	             SmartFile myFile = mySmartUpload.getFiles().getFile(i);
	             
	             if (!myFile.isMissing()) {		
	            	 FileVo vo = this.saveFileInfo(myFile,smartRequest,busiId,funcType,replaceOld);
	            	 JSONObject json = fileVoToJson(vo,request.getContextPath());
	            	 ja.add(json);
	             }
         }
//         if(ret.length()>=1){
//        	 	 ret = ret.substring(1);
//         }
//         ret = "[" + ret + "]";
			
//		return ret;
        return ja.toString();
    }
    
    /**
     * 保存文件信息
     * @param myFile
     * @param smartRequest
     * @param busiId
     * @param funcType
     * @param replaceOld
     * @return
     * @throws AppException
     * @throws IOException
     * @throws SmartUploadException
     */
    private FileVo saveFileInfo(SmartFile myFile,SmartRequest smartRequest,String busiId,String funcType,String replaceOld) throws AppException, IOException, SmartUploadException{
    	String path = PATH + "common" + File.separator;
    	 
    	IFileService busiFileInfo = (IFileService)SpringContextHolder.getBean(IFileService.BEAN_ID); 
     	
    	if(myFile.getSize() == 0){
	 		throw new AppException("不允许上传大小为0的文件！");
	 	}
	 	
		String id = RandomUtil.getUUID();
		
		String clientFileName = smartRequest.getParameter("fileName");			//用户修改后的名称
		
		if(StringUtils.isEmpty(clientFileName)){
			clientFileName = myFile.getFileName();
		}else{
			if(!StringUtils.isEmpty(myFile.getFileExt())){
				clientFileName = clientFileName + "." + myFile.getFileExt();
			}
		}
		
		String serverFileName = id;
		if(!StringUtils.isEmpty(myFile.getFileExt())){
			serverFileName = serverFileName + "." + myFile.getFileExt();
		}
		
		if(clientFileName.length()>64){
			throw new AppException("文件名长度过长，不能超过64个汉字");
		}
		
		FileVo bo = new FileVo();
		bo.setUuid(id);
		bo.setFileName(clientFileName);
		bo.setFileType(funcType);											//功能类型
		bo.setFileFormat(StringUtils.isEmpty(myFile.getFileExt())?"无":myFile.getFileExt());
		bo.setFileSize(BigDecimal.valueOf(myFile.getSize()));
		bo.setDepict(StringUtils.isEmpty(smartRequest.getParameter("fileDesc"))?"无":smartRequest.getParameter("fileDesc"));
		bo.setFileServerPath(path);
		bo.setFileServerName(serverFileName);
		
		if(StringUtils.isEmpty(busiId)){										//新增时，附件的业务ID还没有生成，先传成默认KEY，需要保存成功时更新
			bo.setBusitableKey(AttachmentConstant.ATTACH_EMPTYBUSIKEY);
		}else{
			bo.setBusitableKey(busiId);
			PmDocItemService itemService = (PmDocItemService)SpringContextHolder.getBean("itemService"); 
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("taskId", busiId);
			List<PmDocItemVo> list = itemService.queryForList(map);
			if(Collections3.isNotEmpty(list)){
				bo.setIndexNo(list.get(0).getIndexNo());
			}
		}
		
		SessionUserHolder user = SessionUserUtil.getCurrentUser();
		bo.setCreateEmp(user.getUserName());
		bo.setCreateEmpNo(user.getUserNo());
		bo.setCreateIpaddr(user.getLoginIp());
		bo.setCreateDt(DateUtils.getCurrentDate());
		bo.setIsDel(CommonConstant.COMMON_NO);
    	
		if("true".equals(replaceOld)){								
			busiFileInfo.deleteFileByBusiId(busiId);
		}
		busiFileInfo.insert(bo);									//保存
		
		File pathFile = new File(path);
		boolean isPathExist = pathFile.exists();
		if (!isPathExist)
		     pathFile.mkdirs();
		
		String fullpath = path + serverFileName;
		myFile.saveAs(fullpath);
		
//		String needToPdfFileSuffix = ","+UserEnv.getProp(PropertiesConstant.FILE_2PDF_SUFFIX)+",";
//		if(needToPdfFileSuffix.contains(","+bo.getFileFormat()+",")){			//配置中的文件类型需转换为pdf
//			String sourceFile = fullpath;
//			String destFile = path+"pdf"+File.separator+id+".pdf";
//			new Thread(new Office2PDFThread(sourceFile,destFile)).start();
//		}
		return bo;
    }
    
   /**
    * fileVo 生成返回json数据
    * @param bo
    * @param ctx
    * @return
    */
    private JSONObject fileVoToJson(FileVo bo,String ctx){
    	JSONObject json = new JSONObject();
		json.put("name", bo.getFileName());
		json.put("type", bo.getFileType());
		json.put("success", "true");
		json.put("info", "成功");
		json.put("size", bo.getFileSize());
		json.put("uuid", bo.getUuid());
		json.put("url", ctx+"/servlet/upload?serverFilename="+bo.getUuid());
		json.put("thumbnailUrl", ctx +"/servlet/upload?serverFilename="+bo.getUuid());
		json.put("deleteUrl", ctx +"/servlet/upload?serverFilename="+bo.getUuid()+"&opType=delete");
		json.put("deleteType", "DELETE");
		return json;
    }
    
    /**
	 * 接口方式文件上传（走IUploadService接口）
	 * @param request
	 * @param response
	 * @param mySmartUpload
	 * @throws com.hylandtec.icrm.tl.base.exception.CrmBaseException
     * @throws com.hylandtec.icrm.tl.common.filemanger.SmartUploadException
     * @throws java.io.IOException
	 */
    public String interfaceUpload(HttpServletRequest request, HttpServletResponse response,SmartUpload mySmartUpload) throws AppException, IOException, SmartUploadException{
    	 String path = PATH + "basic" + File.separator;
         
    	 SmartRequest smartRequest = mySmartUpload.getRequest();	
    	 Enumeration<String> pNames = smartRequest.getParameterNames();
    	 Map<String,String> params = new HashMap<String, String>();
    	 while(pNames.hasMoreElements()){
    		 String name = pNames.nextElement();
    		 params.put(name, smartRequest.getParameterValues(name)==null?null:smartRequest.getParameterValues(name)[0]);
    	 }
    	 
         
         FileBasicInfo basicInfo = null;
         String beanName = request.getParameter("beanName");
         if(StringUtils.isEmpty(beanName)){
        	throw new AppException("参数不正确，bean名不能为空！");
         }
         
         JSONArray ja = new JSONArray();
         JSONObject json = new JSONObject();
         
         if (mySmartUpload.getFiles().getCount() > 0) {
             SmartFile myFile = mySmartUpload.getFiles().getFile(0);
             
             if (!myFile.isMissing()) {		
            	 String busiId = RandomUtil.getUUID();
            	 FileVo vo = this.saveFileInfo(myFile, smartRequest,busiId, request.getParameter("funcType"), "false");
            	 json = fileVoToJson(vo,request.getContextPath());
            	 
                
                 basicInfo = new FileBasicInfo();
                 basicInfo.setAttachId(vo.getUuid());
                 basicInfo.setBusiId(busiId);
                 basicInfo.setCname(vo.getFileName());
                 basicInfo.setFileExt(vo.getFileFormat());
                 basicInfo.setPath(path);
                 basicInfo.setSize(vo.getFileSize());
                 basicInfo.setSname(vo.getFileServerName());
                 
                 basicInfo.setCreateEmp(vo.getCreateEmp());
                 basicInfo.setCreateEmpNo(vo.getCreateEmpNo());
                 basicInfo.setCreateIpaddr(vo.getCreateIpaddr());
                 basicInfo.setCreateDt(vo.getCreateDt());
                 basicInfo.setIsDel(vo.getIsDel());
             }
             
             IUploadSingleService uploadService = (IUploadSingleService)SpringContextHolder.getBean(beanName);
             String ret = uploadService.executeOnAfterFileUpload(basicInfo, params);
             if(ret == null){
             	ret = "";
             }
             
             
        }
        
        
        ja.add(json);
        return ja.toString();
    }
    
   /**
    * 其它导入
    * @param request
    * @param response
    * @param mySmartUpload
    * @return	上传的文件的服务器文件名，多个用逗号分隔
    * @throws com.hylandtec.icrm.tl.base.exception.AppException
    * @throws java.io.IOException
    * @throws com.hylandtec.icrm.tl.common.filemanger.SmartUploadException
    */
//    public String otherUpload(HttpServletRequest request, HttpServletResponse response,SmartUpload mySmartUpload) throws AppException, IOException, SmartUploadException{
//    	 String path  = PATH;
//    	 
//    	 SmartRequest smartRequest = mySmartUpload.getRequest();	
//    	 
//    	 IKeyGen keyGen = (IKeyGen)SpringContextHolder.getBean(IKeyGen.BEAN_ID);
//         String ret = "";																		//返回信息
//         for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++) {
//	             SmartFile myFile = mySmartUpload.getFiles().getFile(i);
//	             
//	             if (!myFile.isMissing()) {													
//	            	 	if(myFile.getSize() == 0){
//	            	 		throw new AppException("不允许上传大小为0的文件！");
//	            	 	}
//	            	 	
//		             	String clientFileName = smartRequest.getParameter("fileName");			//用户修改后的名称
//		             	if(StringUtils.isEmpty(clientFileName)){
//		             		clientFileName = myFile.getFileName();
//		             	}else{
//		             		clientFileName += myFile.getFileExt();
//		             	}
//		                String serverFileName =  keyGen.getUUIDKey() + "." + myFile.getFileExt();
//		                 
//		                File pathFile = new File(path);
//		                boolean isPathExist = pathFile.exists();
//		                if (!isPathExist)
//		                     pathFile.mkdirs();
//		                 
//		                String fullpath = path + serverFileName;
//		                myFile.saveAs(fullpath);
//		                 
//		                ret = ret + "," + serverFileName;
//	             }
//         }
//         if(ret.length()>=1){
//        	 	ret = ret.substring(1);
//         }
//         return ret;
//    }
}